<template>
  <div class="">
    <div class="lg:py-11 max-lg:p-4 mx-auto max-w-7xl">
      <div class="lg:grid-cols-4 lg:gap-10 grid grid-cols-1 gap-4">
        <div class="lg:col-span-3 lg:gap-6 flex flex-col col-span-1 gap-4">
          <div class="lg:hidden max-lg:flex flex-col gap-4">
            <h1 class="font-medium text-[1.25rem] text-[#141414]">
              {{ $t('pages.prepaidRefill') }}
            </h1>
            <div class="w-full border-t"></div>
          </div>
          <h2 class="font-medium text-[1.25rem] text-[#121212] lg:flex hidden capitalize">
            {{ $t('formItem.countryRegion') }}
          </h2>
          <h2 class="font-medium text-[0.88rem] text-[#666666] max-lg:flex hidden">
            {{ $t('formItem.countryRegion') }}
          </h2>
          <div class="max-lg:hidden w-full border-t"></div>
          <div class="lg:p-5 p-3 bg-[#FAF9F9] rounded-[1rem] gap-3 flex items-center">
            <div class="lg:size-[2.5rem] size-[1.5rem] overflow-hidden flex-none">
              <img
                v-lazy="$globalFn.imgPrefixUrl(curCountry.icon, 'national_flag')"
                alt="Selected country flag"
                title="Current country flag"
                loading="lazy"
                class="size-full object-cover rounded-full"
              />
            </div>
            <div class="flex-1">
              <el-select
                popper-class="country-popper"
                class="w-full border-none outline-none"
                value-key="iso"
                filterable
                v-model="curCountry"
                :placeholder="$t('formPlaceholder.select')"
                @change="changeCountry($event)"
                @focus="handleSelectClick"
                @hook:mounted="handleSelectClick"
                @visible-change="handleSelectClick"
              >
                <el-option v-for="item in countryList" :key="item.id" :label="item.name" :value="item">
                  <div class="flex gap-4 items-center w-full">
                    <img
                      loading="lazy"
                      class="size-[1.5rem] rounded-[50%]"
                      v-lazy="$globalFn.imgPrefixUrl(item.icon, 'national_flag')"
                      alt="Country flag option"
                      title="Available country flag"
                    />
                    <span class="text-[#666] text-[14px] font-medium">
                      {{ item.name }}
                    </span>
                  </div>
                </el-option>
              </el-select>
            </div>
          </div>
          <!-- h5  输入框适配 -->
          <div class="max-lg:flex hidden flex-col gap-6 w-full">
            <div class="font-medium text-[0.88rem] text-[#666666]">
              {{ $t('pages.rechargeNumber') }}
            </div>
            <div
              class="w-full bg-[#FAF9F9] py-3 px-1 gap-3 rounded-[0.5rem] has-[:focus]:bg-[#FFF4F0] has-[:focus]:border-[#ff4e33] border flex items-center"
            >
              <span class="block font-medium text-[1rem] text-[#666666] text-center flex-none">
                {{ curCountry.phone_code }}
              </span>
              <input
                type="text"
                class="font-medium text-[1rem] !bg-transparent outline-none flex-1 w-[80%]"
                :placeholder="$t('formPlaceholder.input')"
                v-model="phoneNum"
              />
              <span class="el-icon-close flex-none cursor-pointer" v-if="phoneNum.length" @click="phoneNum = ''"></span>
            </div>
          </div>
          <!-- h5  输入框适配 -->
          <div class="font-medium text-[0.88rem] text-[#666666] capitalize">
            {{ $t('pages.supportedOperators') }}
          </div>
          <div class="lg:grid-cols-2 grid grid-cols-1 gap-5">
            <div
              v-for="item in providerList"
              :key="item.provider_code"
              @click="changeProvider(item)"
              class="lg:p-4 p-3 bg-[#FAF9F9] rounded-[0.75rem] flex items-center gap-4 cursor-pointer"
            >
              <div class="size-[3rem] overflow-hidden p-2 bg-white rounded-[0.75rem]">
                <img
                  v-lazy="$globalFn.imgPrefixUrl(item.logo_url, 'goods_thumb_1_1')"
                  alt="Provider logo"
                  title="Mobile operator logo"
                  loading="lazy"
                  class="rounded-[0.63rem] size-full object-contain"
                />
              </div>
              <span class="font-medium text-[0.88rem] text-[#121212] capitalize">
                {{ item.name }}
              </span>
            </div>
          </div>
          <!-- 商品信息 -->
          <!-- 商品信息 -->
          <!-- 商品信息 -->
          <template>
            <h2 class="font-medium text-[1.25rem] text-[#121212] mt-4 capitalize">
              {{ $t('orderPage.goodsInfo') }}
            </h2>
            <template v-if="tel_recharge_desc.content">
              <div class="flex flex-col gap-2">
                <div class="font-medium text-[0.88rem] text-[#666666]">
                  {{ $t('pages.describe') }}
                </div>
                <div class="flex w-full border-t"></div>
              </div>
              <!--  -->
              <div class="simditor">
                <div class="simditor-body overflow-hidden">
                  <div v-html="tel_recharge_desc.content"></div>
                </div>
              </div>
            </template>
            <template v-if="tel_recharge_tips.content">
              <div class="flex flex-col gap-2">
                <div class="font-medium text-[0.88rem] text-[#666666]">
                  {{ $t('pages.guide') }}
                </div>
                <div class="flex w-full border-t"></div>
              </div>
              <div class="simditor">
                <div class="simditor-body overflow-hidden">
                  <div v-html="tel_recharge_tips.content"></div>
                </div>
              </div>
            </template>
          </template>
        </div>
        <!--  充值号码  -->
        <!--  充值号码 -->
        <!--  充值号码-->
        <div class="lg:flex max-lg:hidden col-span-1">
          <div class="relative w-full">
            <div class="top-[8.75rem] sticky flex flex-col gap-6 w-full">
              <h2 class="font-medium text-[1.25rem] text-[#121212] capitalize">
                {{ $t('pages.rechargeNumber') }}
              </h2>
              <div class="w-full border-t"></div>
              <div class="flex flex-col gap-2">
                <div class="font-medium text-[0.75rem] text-[#666666] capitalize">
                  {{ $t('userInfo.phoneNum') }}
                </div>
                <div
                  class="w-full bg-[#FAF9F9] py-3 px-1 gap-3 rounded-[0.5rem] has-[:focus]:bg-[#FFF4F0] has-[:focus]:border-[#ff4e33] border flex items-center"
                >
                  <span class="block font-medium text-[1rem] text-[#666666] text-center flex-none">
                    {{ curCountry.phone_code }}
                  </span>
                  <input
                    type="text"
                    autocomplete="off"
                    class="flex-1 font-medium text-[1rem] !bg-transparent outline-none w-[80%]"
                    :placeholder="$t('formPlaceholder.input')"
                    v-model="phoneNum"
                  />
                  <span class="el-icon-close flex-none cursor-pointer" v-if="phoneNum" @click="phoneNum = ''"></span>
                </div>
              </div>
              <button
                @click="checkPhone"
                class="rounded-[1.5rem] py-3 mt-4 active:scale-95 duration-300 capitalize"
                :class="phoneNum ? 'bg-[#ff4e33] cursor-pointer' : 'bg-[#FFD4C4] cursor-not-allowed  '"
              >
                <span class="font-medium text-[1rem] text-white">
                  {{ $t('formBtn.confirm1') }}
                </span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 手机端底部按钮 -->
    <LazyH5footer>
      <button
        @click="checkPhone"
        class="rounded-[1.5rem] py-3 w-full active:scale-95 duration-300"
        :class="phoneNum ? 'bg-[#ff4e33] cursor-pointer' : 'bg-[#FFD4C4] cursor-not-allowed '"
      >
        <span class="font-medium text-[1rem] text-white">
          {{ $t('formBtn.confirm1') }}
        </span>
      </button>
    </LazyH5footer>
  </div>
</template>
<script>
  import { throttle } from '@/static/js/common'
  export default {
    layout: 'newsHome',
    head() {
      return {
        title: this.goods_category.seo_title,
        meta: [
          {
            hid: 'description',
            name: 'description',
            content: this.goods_category.seo_description
          }
        ]
      }
    },
    data() {
      return {
        curCountry: {}, // 当前选中的国家
        countryList: [], // 国家列表
        providerList: [], // 运营商列表
        loading: true, // 加载状态
        btnLoading: false, // 按钮加载状态
        phoneNum: '', // 手机号码
        tel_recharge_desc: {}, // 充值说明
        tel_recharge_tips: {} // 充值提示
      }
    },
    async asyncData({ app, $cookies }) {
      try {
        // 并发请求获取国家列表和文章内容
        const [countries, rechargeDesc, rechargeTips, goods_category] = await Promise.all([
          app.$axios.get('/api/recharge/getCountries'),
          app.$axios.get('/api/cms.article/read', {
            params: {
              id: '',
              code: 'tel_recharge_desc'
            }
          }),
          app.$axios.get('/api/cms.article/read', {
            params: {
              id: '',
              code: 'tel_recharge_tips'
            }
          }),
          app.$axios.get('/api/goods_category/read', {
            params: {
              code: 'mobile-recharge'
            }
          })
        ])
        // ;
        // ;
        // ;
        return {
          goods_category,
          countryList: countries,
          tel_recharge_desc: rechargeDesc,
          tel_recharge_tips: rechargeTips,
          loading: false
        }
      } catch (error) {
        // 错误处理
        console.error('Failed to fetch initial data:', error)
        return {
          countryList: [],
          tel_recharge_desc: {},
          tel_recharge_tips: {},
          loading: false
        }
      }
    },
    watch: {},
    created() {
      this.handleSelectClick()
      const userSelect = this.$cookies.get('userSelect')
      if (!this.countryList.length) return
      // 设置默认国家
      this.curCountry = this.countryList[0]
      // 如果有用户选择的国家代码,查找匹配的国家
      if (userSelect?.country_code) {
        const selectedCountry = this.countryList.find(item => item.iso === userSelect.country_code)
        // 如果找到匹配的国家则更新当前国家
        if (selectedCountry?.iso) {
          this.curCountry = selectedCountry
        }
      }
      // 获取当前国家的运营商列表
      this.getProvider()
    },
    methods: {
      handleSelectClick(e) {
        if (process.client) {
          this.$nextTick(() => {
            setTimeout(() => {
              document.querySelectorAll('.el-input__inner').forEach(input => {
                input.removeAttribute('readonly')
              })
            }, 200)
          })
        }
      },
      // 获取国家列表
      async getCountry() {
        try {
          const userSelect = this.$cookies.get('userSelect')
          const countries = await this.$axios.get(`/api/recharge/getCountries`)
          this.countryList = countries
          // 如果有国家列表且用户已选择国家
          if (this.countryList.length && userSelect?.country_code) {
            // 查找匹配用户选择的国家
            const matchedCountry = this.countryList.find(item => item.iso === userSelect.country_code)
            // 如果找到匹配的国家则设置为当前国家并获取运营商
            if (matchedCountry?.iso) {
              this.curCountry = matchedCountry
              await this.getProvider()
            }
          }
        } catch (error) {
          console.error('获取国家列表失败:', error)
          this.countryList = []
        }
      },
      //  获取运营商列表
      async getProvider() {
        try {
          this.loading = true
          const res = await this.$axios.get('/api/recharge/getProviders', {
            params: {
              iso: this.curCountry.iso
            }
          })
          this.providerList = res || []
        } catch (error) {
          console.error('获取运营商列表失败:', error)
          this.providerList = []
        } finally {
          this.loading = false
        }
      },
      //  选择国家
      changeCountry(item) {
        this.loading = true
        this.curCountry = item
        this.getProvider()
      },
      //  选择运营商
      changeProvider(item) {
        //this.curProvider = item;
      },
      //  校验手机号
      checkPhone: throttle(
        async function () {
          // 检查必要参数是否存在
          if (!this.curCountry.iso || !this.curCountry.phone_code || !this.phoneNum) {
            return
          }
          try {
            this.btnLoading = true
            const res = await this.$axios.get('/api/recharge/getAccountLookup', {
              params: {
                iso: this.curCountry.iso,
                phone_code: this.curCountry.phone_code,
                phone_number: this.phoneNum
              }
            })
            if (!res) return
            // 查找匹配的运营商
            const matchedProvider = res.items?.[0]?.provider_code
              ? this.providerList.find(item => item.provider_code === res.items[0].provider_code)
              : null
            // 构建路由参数
            const routeInfo = {
              phone: this.phoneNum,
              counrty: this.curCountry,
              provider: matchedProvider || {}
            }
            // 跳转到充值详情页
            await this.$router.push({
              path: this.localePath(`/mobile-recharge/${routeInfo.phone}`),
              query: {
                info: JSON.stringify(routeInfo)
              }
            })
          } catch (error) {
            console.error('查询手机号码失败:', error)
          } finally {
            this.btnLoading = false
          }
        },
        2000,
        {
          leading: true,
          trailing: false
        }
      )
    }
  }
</script>
<style lang="less" scoped>
  // @import "~/assets/css/simditor.css";
  ::v-deep .el-input__inner {
    border: none;
    background-color: transparent;
  }

  .phone-check {
    // margin-top: 96px;
    box-shadow: 0px 12px 48px 16px rgba(0, 0, 0, 0.03), 0px 9px 28px 0px rgba(0, 0, 0, 0.05), 0px 6px 16px -8px rgba(0, 0, 0, 0.08);
  }

  .el-select .el-input input {
    background-color: transparent !important;
  }
</style>
